/**
 * 首页
 * Created by hjy on 2017/9/19.
 */
var Movie = require('../models/movie');
var Catetory = require('../models/catetory');

/**
 * 访问首页
 */
exports.index = function (req,res) {
    console.log("用户session:" );
    console.log(req.session.user);

    Catetory
        .find({})
        .populate({path:'movies',options:{limit:5}})
        .exec(function (err,catetories) {
            if(err){
                console.log(err);
            }

            res.render('index',{
                title:'imooc 首页',
                catetories:catetories
            })
        })
};

/**
 * 显示分类的所有信息
 */
exports.search = function (req,res) {
    var catId = req.query.cat;
    var q = req.query.q;//搜索条件
    var page = parseInt(req.query.p, 10) || 0;
    var count = 2;//每页2条数据
    var index = page * count;

    if(catId){//没有搜索条件
        Catetory
            .find({_id:catId})
            .populate({
                path:'movies',
                select:'title poster',
            })
            .exec(function (err,catetories) {
                if(err){
                    console.log(err);
                }

                var catetory = catetories[0] || [];
                var movies = catetory.movies || [];
                var results = movies.slice(index, index + count);


                res.render('results',{
                    title:'imooc 结果列表页面',
                    keyword:catetory.name,
                    currentPage:(page + 1),
                    query:'cat=' + catId,
                    totalPage:Math.ceil(movies.length / count),
                    movies:results
                })
            })
    }else{//带搜索条件
        Movie
            .find({title:new RegExp(q + '.*')})
            .exec(function (err,movies) {
                if(err){
                    console.log(err);
                }

                var results = movies.slice(index, index + count);


                res.render('results',{
                    title:'imooc 结果列表页面',
                    keyword:q,
                    currentPage:(page + 1),
                    query:'q=' + q,
                    totalPage:Math.ceil(movies.length / count),
                    movies:results
                });

            });
        
    }


};